package com.heima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.heima.reggie.common.R;
import com.heima.reggie.common.Thutil;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class FilterFk implements Filter {

    public AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest res = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String URI = res.getRequestURI();

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/login/**",
                "/user/login",
                "/user/sendMsg"


        };

        boolean chenck = chenck(urls, URI);
        if (chenck) {
            filterChain.doFilter(res, resp);
            return;
        }

        if (res.getSession().getAttribute("employee") != null || res.getSession().getAttribute("user") != null) {
            Thutil.setThreadLocal((Long) res.getSession().getAttribute("employee"));
            Thutil.setThreadLocal((Long) res.getSession().getAttribute("user"));
            filterChain.doFilter(res, resp);

            return;

        }


        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    public boolean chenck(String[] urls, String uri) {

        for (String url : urls) {
            boolean match = antPathMatcher.match(url,uri);
            if (match) {
                return true;
            }


        }
        return false;

    }

}
